<template>
  <div class="container">
    <div>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="考核内容：">
              <el-input
                v-model="select.key"
                placeholder="请输入"
                style="width: 150px"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- <el-col :span="5">
          <el-form ref="form" :model="form">
            <el-form-item label="考核项目：">
              <el-select
                v-model="select.item"
                placeholder="请选择"
                style="width: 150px"
              >
                <el-option
                  v-for="item in select.itemListAll"
                  :key="item.ID"
                  :label="item.ITEMNAME"
                  :value="item.ID"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col> -->
        <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="被考核对象：">
              <el-select
                v-model="select.objectTypeID"
                placeholder="请选择"
                style="width: 150px"
              >
                <el-option
                  v-for="item in select.objectTypeListAll"
                  :key="item.ID"
                  :label="item.nameStr"
                  :value="item.ID"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <el-form ref="form" :model="form" style="float: left">
            <el-form-item>
              <el-button size="mini" type="primary" @click="getInfoList"
                >查 询</el-button
              >
              <el-button size="mini" type="success" @click="handleAdd"
                >新 增</el-button
              >
              <el-button style="padding: 0; border: 0">
                <el-upload
                  action="/上传文件的接口"
                  :on-change="onChange"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept=".xls, .xlsx"
                  class="upload"
                >
                  <el-button size="mini" type="success">导 入</el-button>
                </el-upload>
              </el-button>
              <el-button size="mini" type="warning" @click="exportExcel"
                >导 出</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      highlight-current-row
      :data="items.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
    >
      <el-table-column prop="BH" label="编号" align="center"></el-table-column>
      <!-- 、CONTENT标准描述，POINT扣分值，TIMELIMIT整改时限 -->
      <el-table-column
        prop="TITLE"
        label="考核标题"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="OBJECTTYPE"
        label="被考核对象类型"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="ITEMNAME"
        label="考核项目"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="POINT"
        label="扣分分值"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="TIMELIMIT"
        label="整改时限（日）"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="items.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 弹出框 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="isVisibleEdit"
      width="50%"
    >
      <el-form ref="form" :model="form" label-width="100px" class="flex">
        <el-form-item label="标题" class="wid30">
          <el-input
            v-model="form.TITLE"
            placeholder="请输入"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="被考核对象" class="wid30">
          <el-select
            v-model="form.OBJECTTYPEID"
            class="handle-input mr9"
            placeholder="请选择"
          >
            <el-option
              v-for="item in select.objectTypeListO"
              :key="item.ID"
              :label="item.nameStr"
              :value="item.ID"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="考核项目" class="wid30">
          <el-select v-model="form.ITEMNAME" placeholder="请选择" @change="changeItemEdit">
            <el-option
              v-for="item in select.itemListO"
              :key="item.ITEMNAME"
              :label="item.ITEMNAME"
              :value="item.ITEMNAME"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="扣分分值" class="wid30">
          <el-input
            v-model="form.POINT"
            placeholder="请输入"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="整改时限" class="wid30">
          <el-input
            v-model="form.TIMELIMIT"
            placeholder="请输入"
            class="handle-input mr9"
          ></el-input
          >（日）
        </el-form-item>
        <el-form-item label="考核内容" class="wid30">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2 }"
            show-word-limit
            :rows="9"
            v-model="form.CONTENT"
            placeholder="请输入"
            class="handle-input mr10"
            style="width: 37.5vw"
          >
            <!-- <el-input style="height: 150px;"
            v-model="form.CONTENT"
            autosize
            placeholder="请输入"
            class="handle-input mr10"
          > --></el-input
          >
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'

import export2Excel from '@/utils/exportExcel/index.js'
import OSS from 'ali-oss';
import { time } from 'echarts';
export default {
  data () {

    return {
      clientData: [],
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      originalData: [],
      select: {
        key: '',
        itemID: '',
        objectTypeID: '',
        itemListO: [],
        objectTypeListO: [],
        itemListAll: [],
        objectTypeListAll: [],
      },
      isVisibleEdit: false,
      addDialogTitle: "",
      form: {
        WaterCPH: "",
        WaterTime: "",
        CreateTime: "",
        WaterNumber: "",
        WaterLocation: "",
        WaterCphType: "",
        WaterPeople: "",
        WaterPeopleID: "",
      },
      items: [],
      items1: [
        { ID: '001001', TYPE: '机扫水洗作业道路', NR: '道路积尘', CONTENT: '道路每1千平方积尘不得多余10克', XM: '机扫道路保洁', FZ: '10分', SX: '5天' },
        { ID: '001002', TYPE: '机扫水洗作业道路', NR: '路面垃圾', CONTENT: '道路目视有明显垃圾', XM: '机扫道路保洁', FZ: '10分', SX: '5天' },
        { ID: '001003', TYPE: '机扫水洗作业道路', NR: '道路漏扫', CONTENT: '根据气温条件情况，每年的3月—11月，主次干道每日洗扫不少于2次，喷雾2次，每日洒水不少于6次，高温天气（6、7、8）月每天洒水不少于8次，遇污染天气按大气污染防治办的要求增加次数。其他道路机械化作业的每日洗扫至少1次，喷雾1次，每日洒水不少于2次', XM: '机扫道路保洁', FZ: '10分', SX: '5天' },
        { ID: '001004', TYPE: '机扫水洗作业车辆', NR: '违反交规', CONTENT: '车辆违反交通规则', XM: '机扫道路保洁', FZ: '5分', SX: '3天' },
        { ID: '001005', TYPE: '机扫水洗作业车辆', NR: '车辆报警', CONTENT: '车辆出现报警信息（超速、滞留、疲劳驾驶）', XM: '机扫道路保洁', FZ: '5分', SX: '3天' },
        { ID: '001006', TYPE: '机扫水洗作业车辆', NR: 'GPS定位', CONTENT: '需装配GPS定位装置的环卫作业车辆必须按要求安装并正常使用，如有损坏应及时报备并在72小时内维修到位。/n对未按照要求装配的，1辆/次扣2分/n对人为故意损坏、屏蔽的，1辆/次扣2分/n对未及时维修的，1辆/次扣1分/n车辆出现以上情况，作业视同未作业', XM: '机扫道路保洁', FZ: '5分', SX: '3天' },
        { ID: '002001', TYPE: '人工保洁作业道路', NR: '道路积尘', CONTENT: '道路每1千平方积尘不得多余10克', XM: '人工道路保洁', FZ: '5分', SX: '3天' },
        { ID: '002002', TYPE: '人工保洁作业道路', NR: '七净七无', CONTENT: '七净（车行道净、人行道净、路沿石净、下水篦净、树穴净、绿化带净、边沟净）。保洁时间内做到七无（无废弃堆积物、无碎砖瓦砾砂石、无污泥积水、无果皮纸屑塑模和树叶、无人畜粪便、无烟头、无灰尘痰迹）', XM: '人工道路保洁', FZ: '5分', SX: '3天' },
        { ID: '002003', TYPE: '人工保洁作业道路', NR: '道路漏扫', CONTENT: '一级道路每日作业不少于3次，二级道路每日作业不少于2次，其他道路每日作业不少于1次', XM: '人工道路保洁', FZ: '5分', SX: '3天' },
        { ID: '002004', TYPE: '人工保洁作业人员', NR: '人员报警', CONTENT: '人员工卡报警扣分', XM: '人工道路保洁', FZ: '5分', SX: '3天' },
        { ID: '002005', TYPE: '人工保洁作业人员', NR: '人员考勤', CONTENT: '人员考勤有迟到、早退、缺勤、脱岗等行为扣分', XM: '人工道路保洁', FZ: '5分', SX: '3天' },
        { ID: '004001', TYPE: '公厕', NR: '开放时间', CONTENT: '公厕不按规定时间开放', XM: '公厕', FZ: '5分', SX: '1天' },
        { ID: '004002', TYPE: '公厕', NR: '七净六无', CONTENT: '公共卫生间室内应保持干净整洁，达到“七净六无”。七净：墙壁净、窗口净、玻璃净、地板净、蹲位净、尿池净、内部设施净。六无：无乱写乱画、无尿锈臭味、无污物、无蝇虫、无蜘蛛网、吊灰，内外无积水', XM: '公厕', FZ: '5分', SX: '3天' },
        { ID: '004003', TYPE: '公厕', NR: '乱堆乱放', CONTENT: '公厕管理间及公厕内不允许堆放与公厕无关的物品，保洁工具不得乱摆放，乱晾晒', XM: '公厕', FZ: '5分', SX: '3天' },
        { ID: '004004', TYPE: '公厕', NR: '规章标志', CONTENT: '各项管理规章制度、开放时间、监督电话等应上墙公示；公共卫生间标志应醒目完整，并有亮化设备', XM: '公厕', FZ: '5分', SX: '3天' },
        { ID: '004005', TYPE: '公厕', NR: '外墙整洁', CONTENT: '公厕内外墙不得有小广告，外墙应定期清洗', XM: '公厕', FZ: '5分', SX: '3天' },
        { ID: '004006', TYPE: '公厕保洁人员', NR: '人员考勤', CONTENT: '不得迟到、早退、脱岗和离岗，上岗作业时必须穿工作服', XM: '公厕', FZ: '5分', SX: '3天' },
        { ID: '004007', TYPE: '公厕保洁人员', NR: '文明礼貌', CONTENT: '言语文明、礼貌待人，不得与人发生冲突', XM: '公厕', FZ: '5分', SX: '3天' },
      ],
      options: [{
        XM: '机扫道路保洁'
      }, {
        XM: '人工道路保洁'
      }, {
        XM: '垃圾转运'
      }, {
        XM: '公厕保洁'
      }],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一年',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        },]
      },
      value2: ''
    }
  },

  mounted () {
    this.getObjectTypeList()
    this.getItemList()
    this.getInfoList()
  },
  methods: {
    // changeItemEdit (vauleS) {
    //    this.select.objectTypeListO = this.select.objectTypeListAll.filter(item => item.ITEMNAME === vauleS)
    //    this.form.OBJECTTYPE = ''
    // },
    async getObjectTypeList () {
      var url = 'Assess/GetObjectType_Assess?ITEMID=0&OBJECTTYPE='
      let { data } = await this.$Http.get(url)
      data.forEach(element => {
        element.nameStr = element.OBJECTTYPE + '（' + element.ITEMNAME + '）'
      });
      this.select.objectTypeListO = [...data];
      this.select.objectTypeListAll = data
      this.select.objectTypeListAll.unshift({ ID: "0", OBJECTTYPE: "全部", ITEMNAME: "全部", nameStr: "全部" })
    },
    async getItemList () {
      var url = 'Assess/GetCheckItem_Assess?KEY='
      let { data } = await this.$Http.get(url)
      this.select.itemListO = Object.assign({}, data);
      this.select.itemListAll = data
      this.select.itemListAll.unshift({ ID: "0", ITEMNAME: "全部" })
    },
    async getInfoList () {
      var url = 'Assess/GetStandardDetail_Assess?ITEMID=' + this.select.itemID + '&OBJECTTYPEID=' + this.select.objectTypeID + '&KEY=' + this.select.key
      let { data } = await this.$Http.get(url)
      this.items = data
      // this.screeningData()
    },
    // 打开新增窗口
    handleAdd () {
      this.addDialogTitle = '新增考核标准'
      //清空编辑框
      this.form = {}
      //展示窗口
      this.isVisibleEdit = true;
      // this.idEdit = false;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      this.form = Object.assign({}, row);
      var arr = this.select.objectTypeListO.filter(item => item.OBJECTTYPE === this.form.OBJECTTYPE)
      console.log(arr)
      this.form.OBJECTTYPEID = arr[0].ID
      this.addDialogTitle = '编辑考核标准'
      this.isVisibleEdit = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.addDialogTitle == '新增考核标准') {
        this.form.BH = 0
        this.saveServe('新增')
      }
      if (this.addDialogTitle == '编辑考核标准') {
        this.saveServe('编辑')
      }
    },
    // 保存到服务器
    async saveServe (str) {
      this.$axios({
        url: 'Assess/SaveStandardDetail_Assess',
        method: 'post',
        data: this.form
      }).then(res => {
        // console.log(res)
        if (res.data.IsSucess) {
          this.$message.success(str + '成功')
          this.isVisibleEdit = false
          this.getInfoList()
        } else {
          this.$message.error(str + '失败' + '，' + res.data.Message);
        }
      })
    },
    // 删除
    async handleDelete (index, row) {
      this.form = Object.assign({}, row);
      const confirmResult = await this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult == 'confirm') {
        this.form.BH = -this.form.BH
        this.saveServe('删除')
      } else {
        this.$message.info('取消删除')
      }
    },


    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getlistdata();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    },
    // 导出Excel
    exportExcel () {
      let excelName = '考核细则记录'
      const tHeader = ['考核标题', '被考核对象类型', '考核项目', '扣分分值', '整改时限（日）', '考核内容']
      const filterVal = ['TITLE', 'OBJECTTYPE', 'ITEMNAME', 'POINT', 'TIMELIMIT', 'CONTENT']
      export2Excel(tHeader, filterVal, this.items, excelName)
    },
    // 导入Excel
    onChange (file, fileList) {
      //  console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"// 以字符编码的方式解析
          });

          if (workbook.SheetNames.length >= 1) {
            //  this.$message({
            //    message: "导入数据表格成功",
            //    showClose: true,
            //    type: "success"
            //  });

            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            this.saveStandardList(ws)
            // console.log(ws)
            // this.inputExcelDataLength = ws.length
            // this.fullscreenLoading = this.$loading({
            //   lock: true,
            //   text: 'Loading',
            //   spinner: 'el-icon-loading',
            //   background: 'rgba(0, 0, 0, 0.7)'
            // })
            // for (let i = 0, len = ws.length; i < len; i++) {
            //   var item = ws[i]
            //   this.saveStandardList(item)
            // }
          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },
    async saveStandardList (list) {
      console.log(list)
      list.forEach(element => {
        var formInfo = {}
        formInfo.BH = 0
        formInfo.TITLE = element.标题
        formInfo.CONTENT = element.考核内容
        formInfo.POINT = element.扣分分值
        formInfo.TIMELIMIT = element.整改时限
        switch (element.被考核对象类型) {
          case '机扫水洗作业道路':
            formInfo.OBJECTTYPEID = '1'
            break;
          case '机扫水洗作业车辆':
            formInfo.OBJECTTYPEID = '2'
            break;
          case '人工保洁作业道路':
            formInfo.OBJECTTYPEID = '3'
            break;
          case '人工保洁作业工人':
            formInfo.OBJECTTYPEID = '4'
            break;
          case '公厕':
            formInfo.OBJECTTYPEID = '5'
            break;
          case '垃圾车':
            formInfo.OBJECTTYPEID = '6'
            break;
          case '垃圾收运垃圾点':
            formInfo.OBJECTTYPEID = '7'
            break;
          case '垃圾分类垃圾点':
            formInfo.OBJECTTYPEID = '10'
            break;
          case '垃圾转运站':
            formInfo.OBJECTTYPEID = '8'
            break;
          case '垃圾处理厂':
            formInfo.OBJECTTYPEID = '9'
            break;
          case '果皮箱垃圾点':
            formInfo.OBJECTTYPEID = '11'
            break;
          case '大件垃圾垃圾点':
            formInfo.OBJECTTYPEID = '12'
            break;
          default:
            formInfo.OBJECTTYPEID = '100'
            break;
        }
        this.saveServe111('导入', formInfo)
      });

      // this.items.splice(7, 0, { NR: item['考核内容'], XM: item['考核项目'], FZ: item['扣分分值'], SX: item['整改时限'] })
      // this.$message.success('表格文件导入成功');
      // this.fullscreenLoading.close()
    },
    async saveServe111 (str, formInfo) {
      this.$axios({
        url: 'Assess/SaveStandardDetail_Assess',
        method: 'post',
        data: formInfo
      }).then(res => {
        if (res.data.IsSucess) {
          this.$message.success(str + '成功')
          this.isVisibleEdit = false
          this.getInfoList()
        } else {
          this.$message.error(str + '失败' + '，' + res.data.Message);
        }
      })
    },
  }
}
</script>
<style>
.content {
  overflow-y: scroll;
}
.el-col-6 {
  width: 350px;
  min-height: 50px;
}
.el-table th {
  height: 40px;
}
.el-form-item label {
  width: 80px;
}
</style>